package com.youlai.boot.system.service.impl;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.boot.system.mapper.ProductMapper;
import com.youlai.boot.system.service.ProductService;
import com.youlai.boot.system.model.entity.product;
import com.youlai.boot.system.model.form.productForm;
import com.youlai.boot.system.model.query.productQuery;
import com.youlai.boot.system.model.vo.productVO;
import com.youlai.boot.system.converter.ProductConverter;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;

/**
 * 商品服务实现类
 *
 * @author youlaitech
 * @since 2024-10-22 16:26
 */
@Service
@RequiredArgsConstructor
public class ProductServiceImpl extends ServiceImpl<ProductMapper, product> implements ProductService {

    private final ProductConverter productConverter;

    /**
    * 获取商品分页列表
    *
    * @param queryParams 查询参数
    * @return {@link IPage<productVO>} 商品分页列表
    */
    @Override
    public IPage<productVO> getproductPage(productQuery queryParams) {
        Page<productVO> pageVO = this.baseMapper.getproductPage(
                new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
                queryParams
        );
        return pageVO;
    }
    
    /**
     * 获取商品表单数据
     *
     * @param id 商品ID
     * @return
     */
    @Override
    public productForm getproductFormData(Long id) {
        product entity = this.getById(id);
        return productConverter.toForm(entity);
    }
    
    /**
     * 新增商品
     *
     * @param formData 商品表单对象
     * @return
     */
    @Override
    public boolean saveproduct(productForm formData) {
        product entity = productConverter.toEntity(formData);
        return this.save(entity);
    }
    
    /**
     * 更新商品
     *
     * @param id   商品ID
     * @param formData 商品表单对象
     * @return
     */
    @Override
    public boolean updateproduct(Long id,productForm formData) {
        product entity = productConverter.toEntity(formData);
        return this.updateById(entity);
    }
    
    /**
     * 删除商品
     *
     * @param ids 商品ID，多个以英文逗号(,)分割
     * @return
     */
    @Override
    public boolean deleteproducts(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的商品数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        return this.removeByIds(idList);
    }

}
